import React, { useRef, useEffect, useState } from 'react';
import { Select, Spin, Tag } from 'antd';

import PropTypes from 'prop-types';
// import debounce from 'lodash/debounce';
import { getType } from '@/utils/utils';
import { getEffectSource, everyRequire } from './utils';

const { Option } = Select;
/**
 * 远程搜索 单选多选组合
 */
const SearchInput = React.forwardRef(({ onChange, value, getData, params, ...rest }, ref) => {
    const { selectProps, requireParam, fieldsName } = rest;
    const [loading, setLoading] = useState(false);
    const [list, setList] = useState([]);
    const fetchRef = useRef(null);
    const getOptions = data => {
        // isBuLu 临时处理 加班的业务
        // console.log(data.filter(item => item.employeeCode === 'oa1175979384222339073'));
        if (fieldsName.isBuLu) {
            return data.map(d => (
                <Option value={`${d.employeeCode}-${d.departmentName}`} key={`${d.employeeCode}-${d.departmentName}`}>
                    {d[fieldsName.title]}
                </Option>
            ));
        }
        // 面试模块-根据候选人姓名选择，取出candidateCode字段再去请求
        if (fieldsName.isInterview) {
            return data.map(d => (
                <Option
                    value={d.recruitPost + d.departmentName + d.talentId}
                    key={d.recruitPost + d.departmentName + d.talentId}
                    code={d.candidateCode}
                    title={`${d[fieldsName.title]} - ${d.departmentName} - ${d.recruitPost}`}
                >
                    {d[fieldsName.title]}-{d.departmentName}-{d.recruitPost}
                </Option>
            ));
        }
        // 添加候选人 展示选择候选人名字拼接手机号
        if (fieldsName.candidate) {
            return data.map(d => (
                <Option value={d[fieldsName.value]} key={d[fieldsName.value]}>
                    {d[fieldsName.title]} - {d.talentPhone}
                </Option>
            ));
        }
        // 待我审批详情流程指派 value拼接name
        if (fieldsName.appoint) {
            return data.map(d => (
                <Option value={`${d.userCode}#${d.employeeName}`} key={`${d.userCode}-${d.employeeName}`}>
                    {d[fieldsName.title]}
                </Option>
            ));
        }
        // 待我审批详情流程指派 value拼接name
        if (fieldsName.vacation) {
            return data.map(d => (
                <Option
                    value={d[fieldsName.value]}
                    key={d[fieldsName.value]}
                    info={{
                        departmentCode: d.departmentCode || '',
                        userNo: d.userNo || '',
                        employeeName: d.employeeName || '',
                        employeeCode: d.employeeCode || ''
                    }}
                >
                    {d[fieldsName.title]}
                </Option>
            ));
        }
        if (fieldsName.getemployeebyRole) {
            return data.map(d => (
                <Option value={d[fieldsName.value]} key={d[fieldsName.value]}>
                    {`${d[fieldsName.title]}-${d.postRank}`}
                </Option>
            ));
        }
        if (fieldsName.isEmployee) {
            return data.map(d => (
                <Option
                    value={d[fieldsName.value]}
                    key={d.uuid}
                    label={`${d[fieldsName.title]}（${d.dutyAlias} / ${d.rankValue}）`}
                >
                    {`${d[fieldsName.title]}（${d.dutyAlias} / ${d.rankValue}）`}
                    {d.leaderPositionFlag ? <Tag color="orange">主管</Tag> : null}
                </Option>
            ));
        }
        return data.map(d => (
            <Option value={d[fieldsName.value]} key={d[fieldsName.value]}>
                {d[fieldsName.title]}
            </Option>
        ));
    };

    const fetchList = async (e = null) => {
        const fetchTime = new Date().getTime();
        fetchRef.current = fetchTime;
        if (!everyRequire(params, requireParam)) {
            return;
        }
        setLoading(true);
        const newParams = { ...params, [fieldsName.extraParams]: e };
        const data = await getData(newParams);
        setLoading(false);
        // 用fetchTime与fetchRef.current做比较，用于解决连续两次调用fetchList，
        // 但是第一次请求结果晚于第二次的请求结果，丢弃前面的返回结果，以保证用最后一次请求的数据
        if (fetchTime >= fetchRef.current) {
            setList(data);
        }
    };
    const handleChange = (e, option) => {
        onChange(e, option);
    };
    const handleFilter = (input, option) => {
        if (getType(option.props.children) === 'array') {
            return (
                option.props.children
                    .join('-')
                    .toLowerCase()
                    .indexOf(input.toLowerCase()) >= 0
            );
        }
        return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };
    useEffect(() => {
        fetchList();
    }, getEffectSource(params));
    return (
        <Spin spinning={loading}>
            <Select
                ref={ref}
                showSearch
                value={value}
                defaultActiveFirstOption={false}
                showArrow={false}
                filterOption={handleFilter}
                onChange={handleChange}
                notFoundContent={null}
                allowClear
                getPopupContainer={trigger => trigger.parentElement}
                {...selectProps}
            >
                {getOptions(list)}
            </Select>
        </Spin>
    );
});
SearchInput.propTypes = {
    fieldsName: PropTypes.shape({
        value: PropTypes.any,
        title: PropTypes.string,
        extraParams: PropTypes.string
    }),
    requireParam: PropTypes.array,
    params: PropTypes.object,
    selectProps: PropTypes.object
};
SearchInput.defaultProps = {
    fieldsName: {
        value: 'id',
        title: 'employeeName',
        extraParams: 'userName'
    },
    requireParam: ['companyId'],
    params: {
        companyId: 100
    },
    selectProps: {
        placeholder: '请输入员工姓名',
        allowClear: true
    }
};
export default SearchInput;
